package br.com.myps3t;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class PerfilHelper {
	
	private static Document docPerfil;

	public static void initPerfil(Perfil perfil, String userName) {

		try {

			docPerfil = connectToMyPS3T(userName);

			perfil.setAvatarURLHigh(returnValue("avatar_big"));
			perfil.setAvatarURLLow(returnValue("avatar"));

			perfil.setUserName(returnValue("psn_id"));
			perfil.setUserMessage(returnValue("card_phrase"));

			perfil.setTrophyPlatinum(Integer.parseInt(returnValue("platinum")));
			perfil.setTrophyGold(Integer.parseInt(returnValue("gold")));
			perfil.setTrophySilver(Integer.parseInt(returnValue("silver")));
			perfil.setTrophyBronze(Integer.parseInt(returnValue("bronze")));
			perfil.setUserLevel(Integer.parseInt(returnValue("level")));
			perfil.setUserLevelPorc(Integer.parseInt(returnValue("perc_done")));
			
			perfil.setRegisterDate(returnValue("register_date"));
			
			if ( perfil.getAvatarURLHigh().length() > 0 ) {
				perfil.setImgAvatarHigh(GetImageFromURL(perfil.getAvatarURLHigh()));
			}

			if ( perfil.getAvatarURLLow().length() > 0 ) {
				perfil.setImgAvatarLow(GetImageFromURL(perfil.getAvatarURLLow()));
			}
			
			if ( docPerfil.getElementsByTagName("last_trophy").getLength() > 0 ) {

				UserTrophies userTrophy;
				
				NodeList lastTrophies = docPerfil.getElementsByTagName("last_trophy").item(0).getChildNodes();

				for ( int a = 0; a < lastTrophies.getLength(); a++ ) {

					NodeList infoTrophy = lastTrophies.item(a).getChildNodes();
					
					if ( infoTrophy.getLength() > 0 ) {
					
						String nodeName;
						String nodeValue;
						userTrophy = new UserTrophies();
				
						for ( int b = 0; b < infoTrophy.getLength(); b++ ) {
							
							nodeName = infoTrophy.item(b).getNodeName().trim();
							
							if ( infoTrophy.item(b).getChildNodes().getLength() > 0 ) {
							
								nodeValue = infoTrophy.item(b).getChildNodes().item(0).getNodeValue().trim();

								if ( nodeName.equalsIgnoreCase("name") )
									userTrophy.setNameTrophy(nodeValue);
								if ( nodeName.equalsIgnoreCase("desc") )
									userTrophy.setDescriptionTrophy(nodeValue);
								else if ( nodeName.equalsIgnoreCase("game_id") )
									userTrophy.setGameId(nodeValue);
								else if ( nodeName.equalsIgnoreCase("game_name") )
									userTrophy.setGameName(nodeValue);
								else if ( nodeName.equalsIgnoreCase("type") )
									userTrophy.setTypeTrophy(TrophyType.getByName(nodeValue));
								else if ( nodeName.equalsIgnoreCase("date") )
									userTrophy.setDataConquista(nodeValue);
								else if ( nodeName.equalsIgnoreCase("game_pic") ) {
									
									userTrophy.setGameIcoURL(nodeValue);
									
									if ( nodeValue.length() > 0 )
										userTrophy.setGameIco(GetImageFromURL(nodeValue));

								}
								else if ( infoTrophy.item(b).getNodeName().equalsIgnoreCase("pic") ) {
		
									userTrophy.setImageURLLow(nodeValue);
									
									if ( nodeValue.length() > 0 )
										userTrophy.setImageLow(GetImageFromURL(nodeValue));
									
								}

							}
	
						}
						
						perfil.addTrophy(userTrophy);

					}

				}
			
			}

			if ( docPerfil.getElementsByTagName("ranking").getLength() > 0 ) {

				NodeList rankings;
				int nroRankings = docPerfil.getElementsByTagName("ranking").getLength();

				for ( int nRanks = 0; nRanks < nroRankings; nRanks++ ) {

					rankings = docPerfil.getElementsByTagName("ranking").item(nRanks).getChildNodes();

					if ( rankings.item(1).getNodeName().trim().equalsIgnoreCase("type") ) {
						
						if ( rankings.item(1).getChildNodes().item(0).getNodeValue().trim().equalsIgnoreCase("PointRank object") )
							perfil.setUserPosGeral(Integer.parseInt(rankings.item(3).getChildNodes().item(0).getNodeValue().trim()));
						else if ( rankings.item(1).getChildNodes().item(0).getNodeValue().trim().equalsIgnoreCase("DifiRank object") )
							perfil.setUserPosDif(Integer.parseInt(rankings.item(3).getChildNodes().item(0).getNodeValue().trim()));
						else if ( rankings.item(1).getChildNodes().item(0).getNodeValue().trim().equalsIgnoreCase("RarityRank object") )
							perfil.setUserPosPlat(Integer.parseInt(rankings.item(3).getChildNodes().item(0).getNodeValue().trim()));

					}

				}

			}

		} 
		catch (ParserConfigurationException e) {

			Log.e("ERROR ", e.getMessage());

		}		

	}
	
	private static String returnValue(String elementName) {

		String returnValue = "";
		
		if ( docPerfil.getElementsByTagName(elementName).item(0).getChildNodes().getLength() > 0 )
			returnValue = docPerfil.getElementsByTagName(elementName).item(0).getChildNodes().item(0).getNodeValue();
		
		return returnValue;
	}
	
	public static Bitmap GetImageFromURL(String avatarURL) {

		Bitmap imageRetorno = null;
		
		try {
			
			URI urlImageFile = new URL(avatarURL).toURI();
			imageRetorno = getImageFromCache(urlImageFile.getPath());
			
			if ( imageRetorno == null ) {

				HttpGet httpRequest = new HttpGet(urlImageFile);
				HttpClient httpClient = new DefaultHttpClient();
				HttpResponse response = (HttpResponse)httpClient.execute(httpRequest);
				HttpEntity entity = response.getEntity();
	
				BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
	
				InputStream is = bufHttpEntity.getContent();
				imageRetorno = BitmapFactory.decodeStream(is);

				saveImageToCache(imageRetorno, urlImageFile.getPath());
				
			}

			return imageRetorno;

		} 
		catch (Exception e) {

			Log.e("ERROR ",e.getMessage());

		}

		return imageRetorno;

	}

	private static Bitmap getImageFromCache(String imageFilePath) {

		Bitmap imageRetorno = null;
		File imageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPS3T" + imageFilePath);

		if ( imageFile.exists() )
			imageRetorno = BitmapFactory.decodeFile(imageFile.getPath());
		
		return imageRetorno;

	}
	
	private static void saveImageToCache(Bitmap image, String path) {

		File imageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPS3T" + path);
		File cacheFolder = new File(imageFile.getPath().substring(0, imageFile.getPath().lastIndexOf(File.separator)));
		
		if ( ! cacheFolder.exists() || ! cacheFolder.isDirectory() ) {
			cacheFolder.mkdirs();
		}

		try {

			FileOutputStream fos = new FileOutputStream(imageFile);
			image.compress(CompressFormat.PNG, 100, fos);
			fos.flush();
	        fos.close();

		}
        catch (Exception e) {

			Log.e("ERROR ", e.getMessage());

		}

		
	}

	private static Document connectToMyPS3T(String userName) throws ParserConfigurationException {

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.newDocument();
		
		try {

			String url = "http://www.myps3t.com.br/rank/" + userName.trim() + "/xml/";

			URLConnection urlConn = new URL(url).openConnection();
			InputStream inputStream = urlConn.getInputStream();

			doc = db.parse(inputStream);

			doc.getDocumentElement().normalize();
			
		}
		catch (Exception e) {

			Log.e("ERROR ", e.getMessage());

		}

		return doc;

	}

	/*
	private static void logarCodigo(String writeString) {

		File logFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "teste.txt");

		if (!logFile.exists()) {

			try {

				logFile.createNewFile();

			}
			catch (Exception e) {

				Log.e("ERROR ", e.getMessage());

			}

		}

		try {

			Calendar dataNow = Calendar.getInstance();

			writeString = Integer.toString(dataNow.get(Calendar.DAY_OF_MONTH)) + "-" +  
			              Integer.toString(dataNow.get(Calendar.MONTH)) + "-" +
			              Integer.toString(dataNow.get(Calendar.YEAR)) + " " +
			              Integer.toString(dataNow.get(Calendar.HOUR)) + ":" +
			              Integer.toString(dataNow.get(Calendar.MINUTE)) + ":" +
			              Integer.toString(dataNow.get(Calendar.SECOND)) + " - " +
			              writeString + "|";

			BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
			buf.append(writeString);
			buf.newLine();
			buf.close();

		}
		catch (Exception e) {

			Log.e("ERROR ", e.getMessage());

		}

	}
	*/

}
